﻿
// train-simple-musicDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "TrainSimpleMusic.h"
#include "TrainSimpleMusicDlg.h"
#include "afxdialogex.h"
#include "ConstData.h"
#include <mmsystem.h>
#include <Digitalv.h>
#include"../tool/ErrorHelp.h"
#include "UI/CVoiceSlider.h"
#include "../common-define/cout.h"
#include "../common-define/OwerDefine.h"
#include "../tool/GlobalFunction.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CtrainsimplemusicDlg 对话框

#pragma comment(lib,"winmm.lib")//导入声音的链接库 


void  getMciGetErrorString(MCIERROR error)
{

	wchar_t outError[256];
	// 失败
	mciGetErrorString(error, outError, 256);

	cout << "outError: " << outError << endl;


	MessageBox(NULL, outError, NULL, NULL);

	return;
}

CtrainsimplemusicDlg::CtrainsimplemusicDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_TRAINSIMPLEMUSIC_DIALOG, pParent),
	fileNameByMusic(""),
	lpThumb(nullptr),
	lpActive(nullptr),
	lpNormal(nullptr),
	lpProcessActive(nullptr),
	lpProcessNormal(nullptr),
	mDeviceId(0), 
	millisecond(0),
	loadAddSongMenu(false),
	volumn(16),
	hHandCur(NULL)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	this->mVoiceSlider = new CVoiceSlider();

	this->playModeIconArray[0] = IDB_STOP_PLAY;

	this->playModeIconArray[1] = IDB_PLAY_MODE;

	this->currentPostion = 0;

	this->defaultResourceId = false;

	this->messageCallBack.insert(pair<size_t, void(CtrainsimplemusicDlg::*)(size_t)>(DOUBLE_CLICK_BY_LIST_BOX, &CtrainsimplemusicDlg::doubleClickPlayerByListBox));
	
	this->messageCallBack.insert(pair<size_t, void(CtrainsimplemusicDlg::*)(size_t)>(EDIT_VOICE_FLAG, &CtrainsimplemusicDlg::setVolumn));

	this->messageCallBack.insert(pair<size_t, void(CtrainsimplemusicDlg::*)(size_t)>(WM_SLIDER_SET_CLICK_PROGRESS, &CtrainsimplemusicDlg::setCurrentPlayPostion));

}

void CtrainsimplemusicDlg::setCurrentPlayPostion(size_t currentPostion)
{
	this->currentPostion = currentPostion;

	MCI_PLAY_PARMS PlayParms;

	PlayParms.dwFrom = currentPostion; // 指定从什么地方（时间）播放  
	DWORD ret = mciSendCommand(this->mDeviceId, MCI_SEEK, MCI_WAIT | MCI_NOTIFY | MCI_TO, (DWORD_PTR)&PlayParms);

	if (0 != ret)
	{
		getMciGetErrorString(ret);
		return;
	}

	MCIERROR error = mciSendCommand(this->mDeviceId, MCI_PLAY, MCI_FROM | MCI_NOTIFY, (DWORD_PTR)&PlayParms);

	if (0 != error)
	{
		getMciGetErrorString(error);
		return;
	}
}


void CtrainsimplemusicDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT, volumn);

	DDX_Control(pDX, IDC_EDIT, activeByVoice);

	DDX_Control(pDX, IDC_PLAY_TIME, currentStaticTextTime);
	DDX_Control(pDX, IDC_TOTAL_TIME, totaltaticTextTime);

	DDX_Control(pDX, IDC_SLIDER, *mVoiceSlider);
	DDX_Control(pDX, IDC_CLOSE, mCloseButton);

	DDX_Control(pDX, ID_OPEN, mLastSongButton);
	DDX_Control(pDX, IDC_SUSPEND, mPlayModeButton);
	DDX_Control(pDX, IDC_STOP, mNextSongButton);

	DDX_Control(pDX, IDC_SONG_LIST, listBox);
	DDX_Control(pDX, IDC_PROCESS, mProcess);

}

BEGIN_MESSAGE_MAP(CtrainsimplemusicDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_OPEN, &CtrainsimplemusicDlg::OnBnClickedOpen)
	ON_BN_CLICKED(ID_PLAY, &CtrainsimplemusicDlg::OnBnClickedPlay)
	ON_BN_CLICKED(IDC_SUSPEND, &CtrainsimplemusicDlg::OnBnClickedSuspend)
	ON_BN_CLICKED(IDC_STOP, &CtrainsimplemusicDlg::OnBnClickedStop)
	ON_BN_CLICKED(IDC_ADD_FOLDER, &CtrainsimplemusicDlg::onBnClickedAddMenu)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER, &CtrainsimplemusicDlg::OnNMCustomdrawSlider)
	ON_COMMAND(ID_ADD_FOLDER_MENU, &CtrainsimplemusicDlg::OnBnClickedAddFolder)
	ON_COMMAND(ID_ADD_SONG_FILE_MENU, &CtrainsimplemusicDlg::OnBnClickedOpen)
	ON_WM_NCHITTEST()
	ON_WM_CTLCOLOR()
	ON_WM_TIMER()
	ON_WM_ERASEBKGND()
	ON_BN_CLICKED(IDC_CLOSE, &CtrainsimplemusicDlg::OnBnClickedClose)
	ON_WM_DRAWITEM()
	ON_WM_HSCROLL()
	
END_MESSAGE_MAP()


// CtrainsimplemusicDlg 消息处理程序

BOOL CtrainsimplemusicDlg::OnInitDialog()
{
	
	CDialogEx::OnInitDialog();

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标


	this->hHandCur = this->GetSysHandCursor();

	// TODO: 在此添加额外的初始化代码
	this->BuildShareSlider();

	this->mCloseButton.selectBitMap();
	this->mCloseButton.setTransparent(false);
	

	this->mLastSongButton.selectBitMap(IDB_LAST_SONG);
	this->mNextSongButton.selectBitMap(IDB_NEXT_SONG);
	this->mPlayModeButton.selectBitMap(IDB_STOP_PLAY);

	this->mProcess.init(IDC_ADD_FOLDER);

	

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

//
HCURSOR	CtrainsimplemusicDlg::GetSysHandCursor()
{
	TCHAR		strWinDir[MAX_PATH] = { 0 };
	HCURSOR		hHandCursor = NULL;
	hHandCursor = ::LoadCursor(NULL, MAKEINTRESOURCE(32649));

	// Still no cursor handle - load the WinHelp hand cursor
	if (hHandCursor != NULL)
	{
		return hHandCursor;
	}

	(void)GetWindowsDirectory(strWinDir, MAX_PATH);
	wcscat_s(strWinDir, _T("\\winhlp32.exe"));

	// This retrieves cursor #106 from winhlp32.exe, which is a hand pointer
	HMODULE hModule = ::LoadLibrary(strWinDir);
	DWORD	dwErr = GetLastError();

	if (hModule != NULL)
	{
		HCURSOR	 hTempCur = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
		hHandCursor = (hTempCur != NULL) ? CopyCursor(hTempCur) : NULL;
		FreeLibrary(hModule);
	}
	return hHandCursor;
}

BOOL CtrainsimplemusicDlg::PreTranslateMessage(MSG* pMsg)
{
	
	
	// TODO: 在此添加专用代码和/或调用基类
	if (pMsg->message == WM_KEYDOWN)
	{
		if (pMsg->wParam == VK_ESCAPE || pMsg->wParam == VK_RETURN || pMsg->wParam == VK_SPACE)
			return TRUE;
	}


	return CDialog::PreTranslateMessage(pMsg);
}

void CtrainsimplemusicDlg::OnReleasedcaptureSlider()
{
	

}

// 绘制音量silder 控件
void CtrainsimplemusicDlg::BuildShareSlider()
{
	ASSERT(hHandCur != NULL);

	ASSERT(lpThumb == NULL);

	lpThumb = new CBitItem(IDB_BITMAP_THUMB, 6, 12);

	lpActive = new CBitItem(IDB_BITMAP_ACTIVE, 0, 0);

	lpNormal = new CBitItem(IDB_BITMAP_NORMAL, 0, 0);
	
	mVoiceSlider->SetFlipCursor(hHandCur);
	mVoiceSlider->BuildThumbItem(lpThumb);
	mVoiceSlider->BuildBackItem(lpNormal, lpActive);
	mVoiceSlider->SetTopOffset(3);
	mVoiceSlider->SetRange(0, 500);
	mVoiceSlider->SetLineSize(0);
	mVoiceSlider->SetPos(80);
}



// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CtrainsimplemusicDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		// 绘制对象
		CPaintDC paintDC(this);
		
		this->drawBackground(paintDC);

		this->ReleaseDC(&paintDC);

		CDialogEx::OnPaint();
	}
}

// 绘制背景
void CtrainsimplemusicDlg::drawBackground(CPaintDC& paintDC)
{
	CRect rect;

	this->GetClientRect(&rect);

	CRect copyReact(rect);

	copyReact.bottom = 30;

	// 填充
	paintDC.FillSolidRect(&copyReact, RGB(51, 201, 255));

	// 标题
	CFont font;

	font.CreatePointFont(120, L"微软雅黑");

	paintDC.TextOutW(20, 8, L"迷你播放器");

	//// 读取 位图
	CBitmap bitMap;

	bool res = bitMap.LoadBitmapW(IDB_BITMAP1);

	//// 获取位图信息
	BITMAP bitDataPic;

	bitMap.GetBitmap(&bitDataPic);

	cout << "res" << res << endl;
	//// 创建内存dc
	CDC cdc;

	cdc.CreateCompatibleDC(&paintDC);

	cdc.SelectObject(&bitMap);

	cout << "rect.Width(): " << rect.Width() << endl;

	//// 设置拉伸模式
	paintDC.SetStretchBltMode(HALFTONE);

	//// 拉伸 贴图
	paintDC.StretchBlt(0, 30, rect.Width(), rect.Height(), &cdc, 0, 0, bitDataPic.bmWidth, bitDataPic.bmHeight, SRCCOPY);

	

}

// 消息处理
LRESULT CtrainsimplemusicDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	

	void(CtrainsimplemusicDlg::*func)(size_t) = this->messageCallBack[wParam];

	if (func)
	{
		(this->*func)(lParam);
		return 1;
	}

	cout << "wParam: " << wParam << endl;

	return CDialog::WindowProc(message, wParam, lParam);

}

// 双击listbox 播放歌曲
void CtrainsimplemusicDlg::doubleClickPlayerByListBox(size_t value)
{

	if (value > this->songVector.size() || this->songVector.empty()) {
		return;
	}

	CString str = this->songVector[value];

	if (false == PathFileExists(str))
	{
		MessageBox(DOUBLE_CLICK_ERROR_STRING);

		return;
	}

	this->setCurentSong(str);

	this->setPlayModeIcon();


	this->OnBnClickedPlay();

}


//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CtrainsimplemusicDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CtrainsimplemusicDlg::OnBnClickedOpen()
{
	CFileDialog fileDialogByMusic(true, 
		NULL,
		NULL,
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		FILTER_MUSIC_FILE_NAME
	);

	if (IDOK != fileDialogByMusic.DoModal()) {
		return;
	}


	this->songVector.push_back(fileDialogByMusic.GetPathName());

	this->listBox.AddString(fileDialogByMusic.GetFileName());

	this->editClearStatus();
}

// 设置当前播放歌曲
void CtrainsimplemusicDlg::setCurentSong(const CString& const str)
{

	if (this->mDeviceId)
	{
		this->OnBnClickedStop();
	}

	// 获取选择的文件名
	this->fileNameByMusic = str;


	cout << "this->fileNameByMusic: " << this->fileNameByMusic << endl;

	/*HMODULE res = ::LoadLibrary(L"winmm.lib");

	if (NULL == res)
	{
		MessageBox(L"没有找到winmm.lib");
	}*/

	MCI_OPEN_PARMS mParam;

	mParam.lpstrElementName = this->fileNameByMusic;

	MCIERROR error = mciSendCommand(NULL, MCI_OPEN, MCI_WAIT | MCI_OPEN_ELEMENT, (DWORD_PTR)&mParam);

	if (0 != error)
	{
		getMciGetErrorString(error);
		return;
	}

	this->mDeviceId = mParam.wDeviceID;

	// 获取mp3播放时长

	MCI_STATUS_PARMS mciStatus;

	mciStatus.dwItem = MCI_STATUS_LENGTH;

	mciSendCommand(this->mDeviceId, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);

	this->millisecond = mciStatus.dwReturn;

	// 设置播放进度条数值

	this->mProcess.setTime(mciStatus.dwReturn);

	
}

UINT_PTR CtrainsimplemusicDlg::getMusicInfoItem(size_t dwItem, int *error)
{

	if (this->currentPostion)
	{
		size_t flag = this->currentPostion;

		this->currentPostion = 0;

		*error = 0;

		return flag;
	}

	MCI_STATUS_PARMS mciStatus;

	mciStatus.dwItem = dwItem;

	*error = mciSendCommand(this->mDeviceId, MCI_STATUS, MCI_WAIT | MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);

	if (0 != *error)
	{
		return 0;
	}

	return mciStatus.dwReturn;
}



void CtrainsimplemusicDlg::OnBnClickedPlay()
{
	if (!this->mDeviceId)
	{
		MessageBox(L"错误的音乐标识");
		return;
	}

	// TODO: 在此添加控件通知处理程序代码
	MCI_PLAY_PARMS musicStatus;

	musicStatus.dwCallback = NULL;

	musicStatus.dwFrom = 0;

	this->setVolumn(this->mVoiceSlider->GetPos());

	MCIERROR error = mciSendCommand(this->mDeviceId, MCI_PLAY, MCI_FROM | MCI_NOTIFY, (DWORD_PTR)&musicStatus);

	if (0 != error) {
		getMciGetErrorString(error);
	}

	this->SetTimer(PLAYER_SOUND_TIME, 1000, NULL);


	CString timeStr;

	this->getTotalTime(this->millisecond, &timeStr);


	this->totaltaticTextTime.avoidTextOverlap(timeStr);

}

void CtrainsimplemusicDlg::getTotalTime(size_t millisecond, CString* timeStr) const
{

	size_t second = ceil(millisecond % (1000 * 60) / 1000);

	size_t minute = millisecond / 1000 / 60;

	char secondChar[4];

	char mintureChar[4];

	_itoa_s(second, secondChar, 3, 10);

	_itoa_s(minute, mintureChar, 3, 10);


	CString strSecond(secondChar);

	CString strMinute(mintureChar);

	if (10 > second)
	{
		strSecond = L"0" + strSecond;
	}

	if ( 10 > minute)
	{
		strMinute = L"0" + strMinute ;
	}


	strMinute.Append(_T(":"));

	strMinute.Append(strSecond);

	*timeStr = strMinute;
}


void CtrainsimplemusicDlg::OnBnClickedSuspend()
{
	// TODO: 在此添加控件通知处理程序代码

	this->setPlayModeIcon();

	if (false == this->defaultResourceId)
	{
		mciSendCommand(this->mDeviceId, MCI_PAUSE, NULL, NULL);
	}
	else
	{
		mciSendCommand(this->mDeviceId, MCI_RESUME, NULL, NULL);
	}
}

void CtrainsimplemusicDlg::setPlayModeIcon()
{

	this->defaultResourceId = !this->defaultResourceId;

	this->mPlayModeButton.switchIcon(this->playModeIconArray[this->defaultResourceId]);
}

// 停止播放
void CtrainsimplemusicDlg::OnBnClickedStop()
{
	// TODO: 在此添加控件通知处理程序代码

	MCIERROR error = mciSendCommand(this->mDeviceId, MCI_STOP, NULL, NULL);

	if (0 != error) {
		getMciGetErrorString(error);
	}

	mciSendCommand(this->mDeviceId, MCI_CLOSE, NULL, NULL);

	this->mDeviceId = NULL;
}


void CtrainsimplemusicDlg::OnNMCustomdrawSlider(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);

	this->setVolumn(this->mVoiceSlider->GetPos());
	
	
	*pResult = 0;
}

void CtrainsimplemusicDlg::OnTimer(UINT_PTR nIDEvent)
{

	int error;

	UINT_PTR currentPostion =  this->getMusicInfoItem(MCI_STATUS_POSITION, &error);


	if (currentPostion == this->millisecond || 0 != error)
	{
		this->mProcess.SetRatio(0);

		/// <summary>
		/// 还原图标
		/// </summary>
		/// <param name="nIDEvent"></param>
		this->setPlayModeIcon();

		KillTimer(PLAYER_SOUND_TIME);
		
		return;
	}

	CString str;

	this->getTotalTime(currentPostion, &str);

	this->currentStaticTextTime.avoidTextOverlap(str);

	this->mProcess.SetRatio(currentPostion);

	cout << "nIDEvent: " << nIDEvent << ", time: " << currentPostion << endl;
}



HBRUSH CtrainsimplemusicDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);


	if (CTLCOLOR_STATIC != nCtlColor)
	{
		return hbr;
	}

	int dlgCtrlId = pWnd->GetDlgCtrlID();

	if (IDC_PLAY_TIME == dlgCtrlId || IDC_TOTAL_TIME == dlgCtrlId)
	{
		return hbr;
	}

	pDC->SetTextColor(RGB(0, 0, 0));//设置静态文本框字体颜色
	pDC->SetBkMode(TRANSPARENT);//设置为透明
	return HBRUSH(GetStockObject(HOLLOW_BRUSH));//设置透明这句话不能掉
}

// 设置音量
void CtrainsimplemusicDlg::setVolumn(size_t volumn)
{

	if (!this->mDeviceId)
	{
		return;
	}

	this->volumn = volumn;
	
	cout << "this->volumn: " << this->volumn << endl;

	CString mVolumn;

	mVolumn.Format(L"%d", (int)this->volumn / 5);

	this->activeByVoice.avoidTextOverlap(mVolumn);

	MCI_DGV_SETAUDIO_PARMS setAduio;

	setAduio.dwItem = MCI_DGV_SETAUDIO_VOLUME;

	setAduio.dwValue = this->volumn;

	mciSendCommand(this->mDeviceId, MCI_SETAUDIO, MCI_DGV_SETAUDIO_VALUE | MCI_DGV_SETAUDIO_ITEM, (DWORD_PTR)&setAduio);

}

CtrainsimplemusicDlg::~CtrainsimplemusicDlg()
{
	CDialogEx::~CDialogEx();

	if (lpNormal != NULL)
	{
		delete lpNormal;
		lpNormal = NULL;
	}
	if (lpActive != NULL)
	{
		delete lpActive;
		lpActive = NULL;
	}
	if (lpThumb != NULL)
	{
		delete lpThumb;
		lpThumb = NULL;
	}

	if (lpProcessActive != nullptr)
	{
		delete lpProcessActive;
		lpProcessActive = nullptr;
	}
	if (lpProcessNormal != nullptr)
	{
		delete lpProcessNormal;
		lpProcessNormal = nullptr;
	}

	delete mVoiceSlider;
	mVoiceSlider = nullptr;

	/*delete mProcess;
	mVoiceSlider = nullptr;*/

}

/// <summary>
///  标题区拖动，其他地方不能拖动
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
LRESULT CtrainsimplemusicDlg::OnNcHitTest(CPoint point)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	// 框架调用此成员函数来支持你的应用程序处理 Windows 消息。 
	// 传递到函数的参数反映了收到消息时框架所接收的参数。 
	// 如果调用此函数的基类实现，该实现将使用最初随消息传递的参数，而不是你提供给该函数的参数。
	UINT nHitTest = CDialogEx::OnNcHitTest(point);

	CRect rect;

	this->GetClientRect(&rect);

	rect.bottom = 30;

	// 屏幕坐标系切换为客户端区坐标系，因为两者坐标原点不一样
	ScreenToClient(&point);

	// 鼠标位置是否在标题栏区域
	if (rect.PtInRect(point)) {
		if ( HTCLIENT == nHitTest)
		{
			nHitTest = HTCAPTION;
		}
	}

	return nHitTest;
}

/// <summary>
/// 绘制背景
/// </summary>
/// <param name="pDC"></param>
/// <returns></returns>
BOOL CtrainsimplemusicDlg::OnEraseBkgnd(CDC* pDC)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	return true;
}


void CtrainsimplemusicDlg::OnBnClickedClose()
{
	// TODO: 在此添加控件通知处理程序代码
	EndDialog(IDOK);
}




void CtrainsimplemusicDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
	CDialog::OnHScroll(nSBCode, nPos, pScrollBar);

	// 将滚动框拖到指定位置。 当前位置由 nPos 参数指定。
	if (SB_THUMBTRACK != nSBCode)
	{
		return;
	}

	if (IDC_SLIDER == pScrollBar->GetDlgCtrlID())
	{
		this->setVolumn(this->mVoiceSlider->GetPos());
	}

}

void CtrainsimplemusicDlg::onBnClickedAddMenu()
{
	//获取当前按钮坐标位置
	CPoint point;

	::GetCursorPos(&point);

	if (!this->loadAddSongMenu)
	{
		this->loadAddSongMenu = this->addSongMenu.LoadMenuW(IDR_MENU1);
	}
	

	this->editClearStatus();

	//去掉第一个占位置的
	CMenu* pMenu = addSongMenu.GetSubMenu(0);

	pMenu->TrackPopupMenu(TPM_LEFTALIGN, point.x, point.y, this);

	pMenu = NULL;
	
	

	
}

void CtrainsimplemusicDlg::editClearStatus() 
{
	// 如果列表为空禁用清空列表
	if (0 == songVector.size())
	{
		this->addSongMenu.EnableMenuItem(ID_CLEAR_ALL, MF_GRAYED);
		return;
	}

	this->addSongMenu.EnableMenuItem(ID_CLEAR_ALL, MF_ENABLED);
}


// 添加歌曲文件夹到列表
void CtrainsimplemusicDlg::OnBnClickedAddFolder()
{
	// TODO: 在此添加控件通知处理程序代码
	
	CString folder(L"");

	wchar_t fileBuffer[MAX_PATH];

	// 包含SHBrowseForFolder函数的参数，并接收有关用户选择的文件夹的信息。

	BROWSEINFO bInfo;

	// 返回窗口的窗口句柄。 如果未 CWnd 附加到窗口或用于空指针，则返回 NULL CWnd 。
	bInfo.hwndOwner = this->GetSafeHwnd();

	bInfo.lpszTitle = _T("请选择音乐文件夹");

	bInfo.pidlRoot = NULL;

	// 不要在对话框的树视图控件中的域级别以下包括网络文件夹。| 仅返回文件系统目录。如果用户选择了不属于文件系统的文件夹，则“确定”按钮将显示为灰色。
	bInfo.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS;

	bInfo.pszDisplayName = fileBuffer;

	bInfo.lpfn = NULL;

	bInfo.lParam = NULL;

	// 显示一个对话框，使用户可以选择Shell文件夹。
	LPITEMIDLIST res = SHBrowseForFolder(&bInfo);

	if (!res)
	{
		return;
	}

	// 将项目标识符列表转换为文件系统路径。
	bool coverted =  SHGetPathFromIDList(res, fileBuffer);

	if (false == coverted)
	{
		return;
	}

	folder = fileBuffer;

	// 防止内存泄漏 释放选择文件夹句柄
	IMalloc *malloc;

	if (NOERROR != SHGetMalloc(&malloc)) {
		TRACE(_T("无法打开此文件夹"));
	}

	malloc->Free(res);

	if (malloc)
	{
		malloc->Release();
	}


	//cout << "folder" << folder << endl;

	this->scanFiles(folder);

	this->editClearStatus();

}

bool CtrainsimplemusicDlg::IsSupportFile(const CString& fileName)
{
	CString suffix = fileName.Right(3);

	return suffix.Compare(L"MP3") || suffix.Compare(L"WAV");
}


// 读取文件夹下的所有匹配的文件
void CtrainsimplemusicDlg::scanFiles(const CString& folder)
{
	CFileFind fileFind;

	CString nextTmp = folder;

	CString tmp = folder;

	wchar_t suffix[7] = _T("\\*.*");


	tmp.Append(suffix);

	bool next = fileFind.FindFile(tmp);
	while (next)
	{
		next = fileFind.FindNextFile();
		
		cout << "fileFind.IsDirectory(): " << fileFind.IsDirectory() << endl;
		
		// 如果是"." 则不扫描
		if (fileFind.IsDots())
			continue;

		// 如果是是目录,继续扫描此目录
		else if (fileFind.IsDirectory()) {

			nextTmp = fileFind.GetFilePath();

			this->scanFiles(nextTmp);
		}
		else
		{
			if (false == this->IsSupportFile(fileFind.GetFileName()))
			{
				continue;
			}

			this->songVector.push_back(fileFind.GetFilePath());

			this->listBox.AddString(fileFind.GetFileTitle());
		}
	}
}
